package com.yhh.college_information_platform.controller;

import com.yhh.college_information_platform.annotation.PublicAccess;
import com.yhh.college_information_platform.annotation.RequireAuth;
import com.yhh.college_information_platform.common.PageResult;
import com.yhh.college_information_platform.common.Result;
import com.yhh.college_information_platform.dto.ResourceQueryDTO;
import com.yhh.college_information_platform.dto.ResourceUploadDTO;
import com.yhh.college_information_platform.service.ResourceService;
import com.yhh.college_information_platform.vo.ResourceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资料管理Controller
 *
 * @author yhh
 * @date 2025-10-25
 */
@Slf4j
@RestController
@RequestMapping("/resource")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    /**
     * 分页查询资料列表（游客可访问）
     */
    @PublicAccess
    @PostMapping("/page")
    public Result<PageResult<ResourceVO>> getResourcePage(@RequestBody ResourceQueryDTO queryDTO, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        PageResult<ResourceVO> pageResult = resourceService.getResourcePage(queryDTO, userId);
        return Result.success(pageResult);
    }

    /**
     * 获取最新上传的资料列表（游客可访问）
     */
    @PublicAccess
    @GetMapping("/latest")
    public Result<List<ResourceVO>> getLatestResources(@RequestParam(defaultValue = "10") Integer limit) {
        List<ResourceVO> resources = resourceService.getLatestResources(limit);
        return Result.success(resources);
    }

    /**
     * 获取热门资料列表（游客可访问）
     */
    @PublicAccess
    @GetMapping("/hot")
    public Result<List<ResourceVO>> getHotResources(@RequestParam(defaultValue = "10") Integer limit) {
        List<ResourceVO> resources = resourceService.getHotResources(limit);
        return Result.success(resources);
    }

    /**
     * 获取资料详情（游客可访问）
     */
    @PublicAccess
    @GetMapping("/{id}")
    public Result<ResourceVO> getResourceById(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        ResourceVO resource = resourceService.getResourceById(id, userId);
        return Result.success(resource);
    }

    /**
     * 获取用户上传的资料列表（游客可访问）
     */
    @PublicAccess
    @GetMapping("/user/{userId}")
    public Result<PageResult<ResourceVO>> getUserResources(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        PageResult<ResourceVO> pageResult = resourceService.getUserResources(userId, current, size);
        return Result.success(pageResult);
    }

    /**
     * 增加浏览次数（游客可访问）
     */
    @PublicAccess
    @PostMapping("/{id}/view")
    public Result<Void> incrementViewCount(@PathVariable Long id) {
        resourceService.incrementViewCount(id);
        return Result.success();
    }

    /**
     * 增加下载次数（需要登录）
     */
    @RequireAuth
    @PostMapping("/{id}/download")
    public Result<Void> incrementDownloadCount(@PathVariable Long id) {
        resourceService.incrementDownloadCount(id);
        return Result.success();
    }

    /**
     * 上传文件（需要登录）
     * 单独的文件上传接口，先上传文件获取URL，然后再提交资料信息
     */
    @RequireAuth
    @PostMapping("/upload")
    public Result<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        String fileUrl = resourceService.uploadFile(file);
        
        // 返回文件信息
        Map<String, Object> data = new HashMap<>();
        data.put("fileUrl", fileUrl);
        data.put("fileName", file.getOriginalFilename());
        data.put("fileSize", file.getSize());
        
        // 获取文件类型（扩展名）
        String originalFilename = file.getOriginalFilename();
        String fileType = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        }
        data.put("fileType", fileType);
        
        return Result.success(data);
    }

    /**
     * 上传封面图片（需要登录）
     * 专门用于上传资料的封面图片
     */
    @RequireAuth
    @PostMapping("/upload/cover")
    public Result<Map<String, Object>> uploadCover(@RequestParam("file") MultipartFile file) {
        String coverUrl = resourceService.uploadCoverImage(file);
        
        // 返回封面信息
        Map<String, Object> data = new HashMap<>();
        data.put("coverUrl", coverUrl);
        data.put("fileName", file.getOriginalFilename());
        
        return Result.success(data);
    }

    /**
     * 发布资料（需要登录）
     * 提交资料的完整信息（包括文件URL）
     */
    @RequireAuth
    @PostMapping("/publish")
    public Result<Long> publishResource(@Valid @RequestBody ResourceUploadDTO uploadDTO, 
                                        HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        Long resourceId = resourceService.uploadResource(uploadDTO, userId);
        return Result.success(resourceId);
    }

    /**
     * 删除资料（需要登录，只有上传者本人可以删除）
     */
    @RequireAuth
    @DeleteMapping("/{id}")
    public Result<Void> deleteResource(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        resourceService.deleteResource(id, userId);
        return Result.success();
    }

    /**
     * 更新资料（需要登录，只有上传者本人可以更新）
     */
    @RequireAuth
    @PutMapping("/{id}")
    public Result<Void> updateResource(@PathVariable Long id,
                                       @Valid @RequestBody ResourceUploadDTO uploadDTO,
                                       HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        resourceService.updateResource(id, uploadDTO, userId);
        return Result.success();
    }

    /**
     * 下载资料（需要登录）
     * 返回文件URL和原始文件名
     */
    @RequireAuth
    @GetMapping("/{id}/download")
    public Result<Map<String, String>> downloadResource(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        Map<String, String> downloadInfo = resourceService.getDownloadInfo(id, userId);
        
        return Result.success(downloadInfo);
    }
}

